#!/usr/bin/python
# -*- coding:utf-8 -*-
import requests
import commands
import time
import os
import subprocess
def testurl(url):
    '''test url is return 200'''
    try:
        r = requests.get(url, timeout=5)
        print url,
        print '    .........   ',
        print r.status_code,
        return r.status_code
    except:
        print '服务五秒内没有响应,-_-!'
        return False


def errorlist(status, output):
    if status:
        print "出错了!!!"
        print output
        commands.getstatusoutput('/sh/emaill.py')
        exit('自动更新脚本出错了，我已发邮件通知运维了，防止运维没有及时看到,请电话通知运维。')


shell = '''ssh root@***IP*** -p*** << remotessh
export JAVA_HOME=/usr/local/jdk1.7.0_80
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ps x|grep java |grep /www/pay_8383/ |awk "{print $java}"|xargs kill -9
echo "[`date +%y%m%d/%H:%M:%S`]杀掉进程了" >> /www/pay_8383/logs/catalina.out
sleep 3;
/www/pay_8383/bin/startup.sh
exit
remotessh'''


shell2 = '''ssh root@***IP*** -p*** << remotessh
export JAVA_HOME=/usr/local/jdk1.7.0_80
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ps x|grep java |grep /www/pay_8484/ |awk "{print $java}"|xargs kill -9
echo "[`date +%y%m%d/%H:%M:%S`]杀掉进程了" >> /www/pay_8484/logs/catalina.out
sleep 3;
/www/pay_8484/bin/startup.sh
exit
remotessh'''

(status, output) = commands.getstatusoutput('svn co svn://127.0.0.1:3960/project/Release/ /usr/Release/')
errorlist(status, output)
(status, output) = commands.getstatusoutput("rsync -e 'ssh -p3755' -avzPr --exclude '*.svn' --delete /usr/Release/pay/ root@***IP***:/www/pay_8383/webapps/ROOT/")
errorlist(status, output)
print output
os.system(shell)

time.sleep(6)
i = 0
while True:
    code = testurl('http://***IP***:8383/index1.jsp')
    if code == 200:
        print '8383 OK 开始更新 8484'
        (status, output) = commands.getstatusoutput("rsync -e 'ssh -p3755' -avzPr --exclude '*.svn' --delete /usr/Release/pay/ root@***IP***:/www/pay_8484/webapps/ROOT/")
        errorlist(status, output)
        print output
        os.system(shell2)
        break
    print '8383 还没有起来'
    print '在等等 [5] 秒看看起来了没....'
    time.sleep(5)
    i += 1
    if i == 60:
        print '都一分钟了，服务都还没起来，赶紧叫运维起来干活....'
        print '都一分钟了，服务都还没起来，赶紧叫运维起来干活....'
        print '都一分钟了，服务都还没起来，赶紧叫运维起来干活....'
        print '都一分钟了，服务都还没起来，赶紧叫运维起来干活....'
        os.system('/sh/emaill.py')
        exit('都试了60遍了，服务都还没起来，赶紧叫运维起来干活....')
testurl('http://***IP***:8484/index1.jsp')
